package classes.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : DuJiabao
 * @Date : 2021/1/20 18:36
 * @Project : java_learning
 * @File : null.java
 * @Desc : 线程间通信  进程交替执行
 */
public class Communication {
    public static void main(String[] args) {
        NumberOut numberOut = new NumberOut();
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(numberOut);
        exec.execute(numberOut);
        exec.shutdown();
    }
}

class NumberOut implements Runnable {
    private int num = 100;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();  // 唤醒优先级最高的阻塞线程
//                notifyAll(); //唤醒所有阻塞线程
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + " " + num--);
                    try {
                        wait();   // 进入阻塞态， 等待其他线程唤醒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}

/**
 * 错误的方法，wait()、notify()不能用在ReentranLock()中
 */
class NumberOut2 implements Runnable {
    private int num = 100;
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                notify();  // 唤醒优先级最高的阻塞线程
//                notifyAll(); //唤醒所有阻塞线程
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + " " + num--);
                    try {
                        wait();   // 进入阻塞态， 等待其他线程唤醒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

